<template>
  <el-container style="height: 600px; border: 1px solid #eee">
    <!-- 增加资源的弹出框 -->
    <el-dialog title="新增商品sku" :visible.sync="addFormVisible">
      <!-- 商品编号 -->
      <el-form ref="addForm" :model="addForm" :rules="rules">
        <el-form-item label="商品编号" prop="goods_no" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="addForm.goods_no" autocomplete="off" placeholder="请输入商品编号" />
        </el-form-item>
        <el-button type="primary" @click="searchGoods()">搜索</el-button>

        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="sku_name" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="addForm.sku_name" autocomplete="off" disabled />
        </el-form-item>
        <br>
        <!-- 商品规格 -->
        <div v-for="(item, index) in addForm.specification" :key="index">
          <el-form-item
            :label="item.name"
            :label-width="formLabelWidth"
            required
            style="display:inline-block"
          >
            <div v-if="addForm.specification_select.length>0">
              <el-radio-group v-model="addForm.specification_select[index].value">
                <el-tag type="info" size="mini">规格属性值</el-tag>
                <el-form-item
                  :prop="'specification_select.'+index+'.value'"
                  :rules="[{ required: true, message: '请输入规格属性值', trigger: 'change' }]"
                >
                  <el-radio
                    v-for="(item1, index1) in addForm.specification[index].properties"
                    :key="index1"
                    :label="item1.value"
                  />
                </el-form-item>
              </el-radio-group>
            </div>
          </el-form-item>
        </div>
        <!-- 商品价格 -->
        <el-form-item label="商品价格" prop="price" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="addForm.price" type="number" autocomplete="off" />
        </el-form-item>

        <!-- 商品库存量 -->
        <el-form-item label="商品库存量" prop="repertory" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="addForm.repertory" type="number" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGoodsSku('addForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑资源的弹出框 -->
    <el-dialog title="修改商品类型" :visible.sync="updateFormVisible">
      <el-form ref="updateForm" :model="updateForm" :rules="rules">
        <el-form-item label="商品sku编号" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="updateForm.sku_no" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="updateForm.sku_name" autocomplete="off" disabled />
        </el-form-item>
        <br>
        <div v-for="(item, index) in updateForm.specification" :key="index">
          <el-form-item
            :label="item.name"
            :label-width="formLabelWidth"
            required
            style="display:inline-block"
          >
            <div v-if="updateForm.specification_select.length>0">
              <el-radio-group v-model="updateForm.specification_select[index].value">
                <el-tag type="info" size="mini">规格属性值</el-tag>
                <el-form-item>
                  <el-radio
                    v-for="(item1, index1) in updateForm.specification[index].properties"
                    :key="index1"
                    :label="item1.value"
                  />
                </el-form-item>
              </el-radio-group>
            </div>
          </el-form-item>
        </div>
        <el-form-item label="商品价格" prop="price" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="updateForm.price" type="number" autocomplete="off" />
        </el-form-item>

        <el-form-item label="商品库存量" prop="repertory" :label-width="formLabelWidth" style="display:inline-block">
          <el-input v-model="updateForm.repertory" type="number" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateGoodsSku('updateForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-container>
      <!-- 搜索区 -->
      <el-header>
        <el-input v-model="search.code" placeholder="商品编号" style="width:300px;" />
        <el-input v-model="search.name" placeholder="商品名称" style="width:300px;" />
        <el-button type="primary" icon="el-icon-search" @click="searchGoodsSku()">搜索</el-button>
      </el-header>

      <!-- 功能区 -->
      <el-main style="height:600px;">
        <el-row>
          <el-button type="success" size="mini" @click="add()">增加</el-button>
          <el-button type="primary" size="mini" @click="Edit()">编辑</el-button>
          <el-button size="mini" type="danger" @click="deletes()">删除</el-button>
        </el-row>
        <!-- 表格 组件 -->
        <datatable
          :table-fomat="tableFomat"
          :table-data="tableData"
          :total="tableData.length"
          @handleEdit="handleEdit"
          @handleDelete="handleDelete"
          @handleSelectionChange="handleSelectionChange"
        >
          <el-table-column label="规格" width="200">
            <template slot-scope="scope">
              <el-tag
                v-for="(ele,index) in scope.row.specification_select"
                :key="index"
                type="info"
                style="margin: 0px 2px"
              >{{ ele.name }}: {{ ele.value }}</el-tag>
            </template>
          </el-table-column>
        </datatable>
      </el-main>
    </el-container>
  </el-container>
</template>
<style>
/* 容器头部 和  */
.el-header {
  line-height: 60px;
}
.el-aside {
  width: 200px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  color: #333;
  background-color: white;
}
</style>
<script>
import datatable from '@/views/my-views/components/table'
import goods from '@/sql/table-field/index'
import { tsFormatTime } from '@/tools/util'
import { mapGetters } from 'vuex'
import FlakeId from 'flake-idgen'
import informat from 'biguint-format'
// 使用雪花算法生成商品的编号
var flakeIdGen = new FlakeId()
export default {
  name: 'GoodsSkuList',
  components: {
    datatable
  },
  data() {
    return {
      // 表单认证规则
      rules: {
        goods_no: [
          { required: true, message: '请输入商品编号', trigger: 'blur' }
        ],
        sku_name: [
          { required: true, message: '商品名称不能为空', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        repertory: [
          { required: true, message: '请输入商品库存量', trigger: 'blur' }
        ]
      },
      // 解决notice通知栏覆盖问题
      notifyPromise: Promise.resolve(),
      // 搜索输入框的值
      // 搜索输入框的值
      search: {
        code: '',
        name: ''
      },
      // 表格显示格式(列名以及列对应显示的数据)
      tableFomat: goods.goodsSku,
      // 表格数据
      tableData: [],
      // 当前表格选中的数据
      multipleSelection: [],

      // 增加的弹出框设置
      addFormVisible: false,
      addForm: {
        // 商品的id
        goods_spu_id: '',
        // 商品编号--用于搜索商品
        goods_no: '',
        // sku商品编号
        sku_no: '',
        // 商品的名字
        sku_name: '',
        // 商品价格
        price: 0,
        // 商品规格
        specification: [
          {
            id: '',
            name: '',
            properties: [
              {
                value: ''
              }
            ]
          }
        ],
        // 已选规格
        specification_select: [],
        // 商品库存
        repertory: 0
      },
      formLabelWidth: '120px',
      // 搜索的商品
      goods: {},
      // 修改的弹出框设置
      updateFormVisible: false,
      updateForm: {
        // 商品sku的id
        _id: '',
        // sku商品编号
        sku_no: '',
        // 商品的名字
        sku_name: '',
        // 商品价格
        price: 0,
        // 商品规格
        specification: [
          {
            id: '',
            name: '',
            properties: [
              {
                value: ''
              }
            ]
          }
        ],
        // 已选规格
        specification_select: [],
        // 商品库存
        repertory: 0
      }
    }
  },
  computed: {
    // 从store中的getters中获取数据(store/getters.js)
    ...mapGetters(['goodsSkuList'])
  },
  mounted() {
    // 如果state中有数据则从state中读取
    if (this.goodsSkuList.length !== 0) {
      // 使用缓存
      this.tableData = this.goodsSkuList
    } else {
      // 获取商品列表
      this.getGoodsSkuList()
    }
  },

  methods: {
    // 搜索商品
    searchGoods() {
      const type = '搜索'
      this.$store
        .dispatch('getGoodsByGoodsNo', this.addForm)
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            if (res.data.length === 0) {
              this.$message({
                type: 'warning',
                message: '该商品不存在'
              })
            } else {
              const goods = []
              res.data.forEach(value => {
                goods.push(JSON.parse(value))
              })
              this.goods = goods[0]
              this.addForm.specification = this.goods.specification
              this.addForm.specification_select = this.goods.specification.map(
                res => {
                  return {
                    id: res.id,
                    name: res.name,
                    value: ''
                  }
                }
              )
              this.addForm.goods_spu_id = this.goods._id
              this.addForm.sku_name = this.goods.goods_name
            }
          }
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    // 搜索Sku商品
    searchGoodsSku() {
      const type = '搜索'
      this.$store
        .dispatch('searchGoodsSku', this.search)
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
          }
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    // 商品类型id填写到表单
    handlechange(value, name) {
      if (name === 'addForm.type_id') {
        this.addForm.type_id = value[value.length - 1]
      } else if (name === 'updateForm.type_id') {
        this.updateForm.type_id = value[value.length - 1]
      }
    },
    // tip提示方法
    tipformat(res, type, type_name) {
      if (res.errcode !== 0) {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify.error({
              title: `${type}商品失败`,
              message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
              duration: 0
            })
          })
      } else {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify({
              title: `${type}商品成功`,
              message: `${type_name}--商品${type}成功`,
              type: 'success',
              duration: 6000
            })
          })
        // 重新从数据库获取数据
        this.getGoodsSkuList()
      }
    },
    // 数据库数据转换为前端显示数据格式
    dataBaseToFormData(value) {
      value.create_time = tsFormatTime(value.create_time, 'Y-M-D h:m:s')
      value.update_time = tsFormatTime(value.update_time, 'Y-M-D h:m:s')
      return value
    },
    // 错误请求消息提示规范
    catchError(type, err) {
      this.$notify.error({
        title: `${type}商品请求失败`,
        message: err,
        duration: 0
      })
    },
    // 添加商品sku
    addGoodsSku(formName) {
      const type = '添加'
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addFormVisible = false
          // 使用雪花算法写出十进制的商品编号
          this.addForm.sku_no = informat(flakeIdGen.next(), 'dec')
          this.$store
            .dispatch('addGoodsSku', this.addForm)
            .then(res => {
              // 清空文件列表
              console.log(res)
              // 正常请求消息提示规范
              this.tipformat(res, type, this.addForm.sku_name + 'sku')
            })
            .catch(err => {
              // 错误请求消息提示
              this.catchError(type, err)
            })
        } else {
          return false
        }
      })
    },
    // 修改商品sku信息
    updateGoodsSku(formName) {
      const type = '修改'
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.updateFormVisible = false
          this.$store
            .dispatch('updateGoodsSku', this.updateForm)
            .then(res => {
              this.tipformat(res, type, this.updateForm.sku_name + 'sku')
            })
            .catch(err => {
              this.catchError(type, err)
            })
        } else {
          return false
        }
      })
    },
    // 获取商品列表的方法
    getGoodsSkuList() {
      const type = '获取'
      this.$store
        .dispatch('getGoodsSkus')
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
            this.$store.commit('setGoodsSkuList', this.tableData)
          }
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 每列的编辑
    handleEdit(index, row) {
      this.updateFormVisible = true
      this.updateForm._id = row._id
      this.updateForm.sku_no = row.sku_no
      this.updateForm.sku_name = row.sku_name
      this.updateForm.repertory = row.repertory
      this.updateForm.price = row.price
      this.updateForm.specification = JSON.parse(
        JSON.stringify(row.goods_spu[0].specification)
      )
      this.updateForm.specification_select = JSON.parse(
        JSON.stringify(row.specification_select)
      )
    },
    // 每列的删除
    handleDelete(index, row) {
      const type = '删除'
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$store
            .dispatch('deleteGoodsSkuById', row)
            .then(res => {
              this.tipformat(res, type, row.sku_name)
            })
            .catch(err => {
              this.catchError(type, err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 头部的添加
    add() {
      this.addFormVisible = true
      // 商品编号
    },
    // 头部的编辑
    Edit() {
      if (this.multipleSelection.length === 1) {
        this.updateFormVisible = true
        this.updateForm._id = this.multipleSelection[0]._id
        this.updateForm.sku_no = this.multipleSelection[0].sku_no
        this.updateForm.sku_name = this.multipleSelection[0].sku_name
        this.updateForm.repertory = this.multipleSelection[0].repertory
        this.updateForm.price = this.multipleSelection[0].price
        this.updateForm.specification = JSON.parse(
          JSON.stringify(this.multipleSelection[0].goods_spu[0].specification)
        )
        this.updateForm.specification_select = JSON.parse(
          JSON.stringify(this.multipleSelection[0].specification_select)
        )
      } else {
        this.$message('你有且必须选择一条数据')
      }
    },
    // 头部的删除
    deletes() {
      const type = '删除'
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.multipleSelection.length >= 1) {
            this.$store
              .dispatch('deleteGoodsSkuByIds', this.multipleSelection)
              .then(res => {
                for (let i = 0; i < this.multipleSelection.length; i++) {
                  this.tipformat(
                    res[i],
                    type,
                    this.multipleSelection[i].sku_name + 'sku'
                  )
                }
              })
              .catch(err => {
                this.catchError(type, err)
              })
          } else {
            this.$notify({
              title: `至少一条数据`,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
